<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useNaiveForm } from '@/hooks/common/form';
import { fetchGetAllRoles, fetchGetDeptTree } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions, genderOptions } from '@/constants/business';

defineOptions({
  name: 'UserOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.User | null;
  /** selected department id */
  selectedDeptId?: number | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.SystemManage.User,
  'userName' | 'nickName' | 'gender' | 'telephone' | 'email' | 'status' | 'userRoles'
> & {
  id: number;
  deptId: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: 0,
    userName: '',
    nickName: '',
    gender: null,
    telephone: '',
    email: '',
    userRoles: [],
    status: 1,
    deptId: props.selectedDeptId || null
  };
}

// 表单校验规则
const rules = {
  userName: [
    {
      required: true,
      message: $t('page.manage.user.form.userName'),
      trigger: ['input', 'blur']
    }
  ],
  nickName: [
    {
      required: true,
      message: $t('page.manage.user.form.nickName'),
      trigger: ['input', 'blur']
    }
  ],
  email: [
    {
      required: true,
      message: $t('page.manage.user.form.email'),
      trigger: ['input', 'blur']
    },
    {
      type: 'email',
      message: $t('form.email.invalid'),
      trigger: ['input', 'blur']
    }
  ]
};

/** the enabled role options */
const roleOptions = ref<CommonType.Option<string>[]>([]);

const deptTreeOptions = ref();

async function getRoleOptions() {
  const { error, data } = await fetchGetAllRoles();

  if (!error) {
    const options = data.map(item => ({
      label: item.roleName,
      value: item.roleKey
    }));

    roleOptions.value = options;
  }
}

async function getDeptTreeOptions() {
  const { error, data } = await fetchGetDeptTree();

  if (!error) {
    deptTreeOptions.value = [...data];
  }
}

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }

  // 如果有选中的部门，设置为默认部门
  if (props.selectedDeptId && props.operateType === 'add') {
    model.deptId = props.selectedDeptId;
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request

  window.$message?.success($t('common.updateSuccess'));
  closeModal();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    getRoleOptions();
    getDeptTreeOptions();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" preset="dialog" :title="title" style="width: 800px; max-width: 90vw; height: 60vh">
    <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="120">
      <NGrid :cols="2" :x-gap="16">
        <NFormItemGi :label="$t('page.manage.user.userName')" path="userName">
          <NInput v-model:value="model.userName" :placeholder="$t('page.manage.user.form.userName')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.user.nickName')" path="nickName">
          <NInput v-model:value="model.nickName" :placeholder="$t('page.manage.user.form.nickName')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.user.gender')" path="gender">
          <NRadioGroup v-model:value="model.gender">
            <NRadio v-for="item in genderOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.user.telephone')" path="telephone">
          <NInput v-model:value="model.telephone" :placeholder="$t('page.manage.user.form.telephone')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.user.email')" path="email">
          <NInput v-model:value="model.email" :placeholder="$t('page.manage.user.form.email')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.organization.belongDept')" path="deptId">
          <NTreeSelect
            v-model:value="model.deptId"
            :options="deptTreeOptions"
            :placeholder="$t('page.manage.organization.selectDept')"
            clearable
            filterable
            show-path
            separator=" / "
            key-field="value"
            label-field="label"
            children-field="children"
          />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.user.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItemGi>

        <NFormItemGi :span="2" :label="$t('page.manage.user.userRole')" path="userRoles">
          <NSelect
            v-model:value="model.userRoles"
            multiple
            :options="roleOptions"
            :placeholder="$t('page.manage.user.form.userRole')"
          />
        </NFormItemGi>
      </NGrid>
    </NForm>

    <template #action>
      <NSpace>
        <NButton @click="closeModal">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
